#!/usr/bin/python
#-*- coding: utf-8 -*-

import re
import httplib, urllib
import sqlite3

con = sqlite3.connect('baseline_data.sqlite')
cur = con.cursor()

conn = httplib.HTTPConnection("www.xrayrisk.com")
gender = ('Male', 'Female')

for sex in gender:
    for i in range(100):
        params = urllib.urlencode({'gender': sex, 'age': i + 1, 'num_exams': '10', 'dose': '10.0', 'id': '1', 'action': 'calculate', 'studyname': 'Chest x-ray (2 views)', 'convert_factor': '1.00000', 'actual': 'Optional'})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        conn.request("POST", "/calculator/calculator-normal-studies.php", params, headers)
        resp = conn.getresponse()
        data = resp.read()    
        a_risk = re.findall(r"<input.*name=\"additional_cancer_risk\".*\svalue=\"(.*?)\"", data)
        
        igender = 0
        if sex == 'Male':
            igender = 1
        
        query = "INSERT INTO cancer_risk (sex, age, risk) VALUES (" + str(igender) + ", " + str(i + 1) + ", " + str(a_risk[0]) + ")"
        print "Inserting %s with age %d and risk %s" % (sex, i + 1, a_risk[0])
        cur.execute(query)
        
conn.close()
con.commit()
con.close()